package com.zcl.Thread.t4;

/**
 * @Description:
 * @author: zcl
 * @date: 2022/3/9  17:05
 *
 * synchronized(同步监视器锁){
 *     //需要被同步的代码块
 * }
 * 1.操作共享数据的代码,即为需要被同步的代码
 * 2.共享数据: 多个线程共同操作的变量,比如ticket就是共享数据TestTicket.java
 * 3.同步监视器锁: 俗称: 锁. 任何一个类的对象,都可以充当锁.但必须满足的是: 多个线程必须要共用同一把锁
 *
 *
 */

class Method implements Runnable {
    private int ticket = 100;
//    Object o = new Object();


    @Override
    public void run() {


            while (true) {
//                synchronized (this) { //此时的this是调用run()方法的对象
//                synchronized (o) {
                synchronized (this.getClass()){

                if (ticket > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ": 卖票,票号为: " + ticket);
                    ticket--;
                } else {
                    break;
                }
            }
        }
    }
}

public class TicketMethod {
    public static void main(String[] args) {
        Method method = new Method();
        Thread thread1 = new Thread(method);
        Thread thread2 = new Thread(method);
        Thread thread3 = new Thread(method);
        thread1.setName("窗口1");
        thread2.setName("窗口2");
        thread3.setName("窗口3");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}
